package com.gtt.lazy.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;

import com.gtt.lazy.domain.User;
import com.gtt.lazy.service.UserService;
import com.gtt.lazy.util.HibernateTemplateUtil;

public class UserServiceImpl implements UserService {

	private static final Logger logger = Logger
			.getLogger(UserServiceImpl.class);
	private HibernateTemplateUtil hibernateTemplateUtil;

	public int add(User user) {
		if (logger.isDebugEnabled())
			logger.debug("add User");
		return (Integer) hibernateTemplateUtil.save(user);
	}

	public void update(User user) {
		if (logger.isDebugEnabled())
			logger.debug("update User");
		hibernateTemplateUtil.update(user);
	}

	public User get(int id) {
		return (User) hibernateTemplateUtil.get(User.class, id);
	}

	@SuppressWarnings("unchecked")
	public boolean exist(User user) {
		String hql = "from User as u where u.username=? and u.password=?";
		List list = hibernateTemplateUtil.find(hql, new Object[] {
				user.getUsername(), user.getPassword() }, new Type[] {
				Hibernate.STRING, Hibernate.STRING });
		return list.size() > 0;
	}

	@SuppressWarnings("unchecked")
	public boolean existUser(String username) {
		String sql = "from User as u where u.username=?";
		List list = hibernateTemplateUtil.find(sql, new Object[] { username },
				new Type[] { Hibernate.STRING });
		return list.size() > 0;
	}

	@SuppressWarnings("unchecked")
	public User findByUsername(String username) {
		String sql = "from User as u where u.username=?";
		List<User> list = hibernateTemplateUtil.find(sql,
				new Object[] { username }, new Type[] { Hibernate.STRING });
		return list.size() > 0 ? list.get(0) : null;
	}

	public HibernateTemplateUtil getHibernateTemplateUtil() {
		return hibernateTemplateUtil;
	}

	public void setHibernateTemplateUtil(
			HibernateTemplateUtil hibernateTemplateUtil) {
		this.hibernateTemplateUtil = hibernateTemplateUtil;
	}

}
